package com.das.mechanic_base.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;

import androidx.annotation.Nullable;

import com.das.mechanic_base.utils.X3ScreenUtils;

import java.lang.ref.WeakReference;

public class X3AloneSoundView extends View {

    private WeakReference<Context> mContext;
    private Paint mPaint;
    private float[] waveWidth;
    private float[] waveAmplitude;
    private int[] wavePhase;

    private float phase = 0;
    private float midWidth;

    public X3AloneSoundView(Context context) {
        this(context,null);
    }

    public X3AloneSoundView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public X3AloneSoundView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = new WeakReference<Context>(context);
        initPaint();
    }

    private void initPaint() {
        // 初始化画笔
        mPaint = new Paint();
        Context ctx = mContext.get();
        if (ctx != null){
            mPaint.setStrokeWidth(X3ScreenUtils.dipToPx(1,ctx));// 画线宽度
        }
        mPaint.setStyle(Paint.Style.STROKE);//空心效果
        mPaint.setAntiAlias(true);//抗锯齿
        mPaint.setColor(Color.parseColor("#0077FF"));

        waveWidth = new float[]{1, 1};
        DisplayMetrics metric = getResources().getDisplayMetrics();
        float density = metric.density; // 屏幕密度
        for (int i = 0; i < waveWidth.length; i++) {
            waveWidth[i] = waveWidth[i] * density / 2;
        }

        waveAmplitude = new float[]{0.7f, 0.4f};
        /**
         * 主波纹与副波纹有某点重叠 故需要将副波纹进行偏移
         */
        wavePhase = new int[]{6, 12};

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        float period = 1.5f;// 区域内，正弦波的周期
        mPaint.setColor(Color.parseColor("#0077FF"));
        if (mContext.get() == null ){
            return;
        }
        mPaint.setStrokeWidth(X3ScreenUtils.dipToPx(1,mContext.get()));

        // 将绘图原点移动到区域中心
        int width = getWidth();
        int height = getHeight();
        midWidth = width / 2.0f;
        float midHeight = (height - X3ScreenUtils.dipToPx(4,mContext.get()))/ 2.0f;
        canvas.translate(midWidth, midHeight + X3ScreenUtils.dipToPx(2,mContext.get()));

        // 初始化线条
        Path sinPath = new Path();
        sinPath.moveTo(-midWidth, X3ScreenUtils.dipToPx(10,mContext.get()));

        // 计算线条
        for (float x = -midWidth; x < midWidth; x++) {
            double sine = Math.sin(2 * Math.PI * period * ((x + phase) / width));//计算该点上的正弦值
            float y = (float) (midHeight * sine);// 将正弦值限定到绘图区的高度上
            sinPath.lineTo(x, y);
        }

        canvas.drawPath(sinPath, mPaint);//绘制线条

        // 副波纹
        for (int i = 0; i < waveWidth.length; i++) {
            mPaint.setStrokeWidth(waveWidth[i]);//画笔宽度
            mPaint.setAlpha((int) (0.6f * 255));//画笔透明度

            sinPath.reset();//重置线条
            sinPath.moveTo(-midWidth, 0);

            // 计算线条
            for (float x = -midWidth; x < midWidth; x++) {
                double scaling = 1 - Math.pow(1 / midWidth * x, 2);
                double sine = Math.sin(2 * Math.PI * period * ((x + phase + wavePhase[i]) / width));//计算该点上的正弦值
                float y = (float) ((midHeight + i * X3ScreenUtils.dipToPx(2,mContext.get()))// 将正弦值限定到绘图区的高度上
                        * sine   // 正弦值
                        * scaling// 振幅修正 - 距离中心越远，振幅越小
                        * waveAmplitude[i]// 副波纹振幅修正
                );
                sinPath.lineTo(x, y);
            }

            canvas.drawPath(sinPath, mPaint);//绘制线条
        }
       // canvas.restore();
    }

    Handler handler = new Handler();

    static class RefreshRunnable implements Runnable{
        WeakReference<Context> ctx;
        WeakReference<X3AloneSoundView> mX3AloneSoundView;
        public RefreshRunnable(Context ctx,X3AloneSoundView mX3AloneSoundView){
            this.ctx = new WeakReference<>(ctx);
            this.mX3AloneSoundView = new WeakReference<>(mX3AloneSoundView);
        }
        @Override
        public void run() {
            if (ctx.get()!=null && mX3AloneSoundView.get()!=null){
                mX3AloneSoundView.get().phase -= X3ScreenUtils.getScreenWidth(ctx.get())/10;
                mX3AloneSoundView.get().invalidate();
                mX3AloneSoundView.get().handler.postDelayed(this,130);
            }
        }
    }

    public void startAnim() {
        handler.post(new RefreshRunnable(mContext.get(),this));
    }

    public void stopAnim() {
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }
}
